<!--
 * @Author: zhangyonggui
 * @Date: 2023-10-25 15:20:50
 * @LastEditors: zhangyonggui
 * @LastEditTime: 2024-01-20 10:55:54
 * @Descripttion:
-->
<template>
  <el-dialog
    :title="title"
    v-model="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :modal-append-to-body="false"
    width="50%"
  >
    <div class="dialog-body">
      <div class="asset-count">已选择 {{ assetCount }} 条数据</div>
      <div class="tag-container">
        <el-autocomplete
          v-if="inputVisible"
          ref="saveTagInput"
          popper-class="my-autocomplete"
          :popper-append-to-body="false"
          v-model.trim="inputValue"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入内容"
          size="default"
          @select="handleSelect"
          @keyup.enter.native="handleInputConfirm"
          @blur="cancelInput"
        >
          <template #default="{ item }">
            <div class="name">{{ item.name }}</div>
          </template>
          <template #suffix>
            <el-icon class="el-input__icon" @click="handleInputConfirm">
              <check />
            </el-icon>
          </template>
        </el-autocomplete>
        <div v-else class="new-tag" @click="showInput">+ 新增公司</div>

        <div class="tag" v-for="(tag, index) in reverseArray" :key="index">
          <span>{{ tag.tag }}</span>
          <i
            v-if="tag.modifiable"
            class="tag-close el-icon-close"
            @click="handleClose(tag)"
          ></i>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
      <el-button size="small" @click="cancel">取 消</el-button>
      <el-button type="primary" size="small" @click="confirm">确 定</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup> 
import {defineProps,defineEmits, watch,ref,computed,nextTick,Ref} from 'vue';
import {ElMessage} from 'element-plus'
import {useStore} from 'vuex';
const store =useStore();
const emit=defineEmits(['update:isShow','addCompanys']);
const props=defineProps({
  isShow: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '确认',
    },
    batchCompanyType: {
      type: String,
      default: '',
    },
    selectType: {
      type: Number,
      default: 0,
    },
    searchData: {
      type: Object,
      default: () => {
        return {}
      },
    },
    assetIds: {
      type: Array,
      default: () => [],
    },
    assetCount: {
      type: Number,
      default: 0,
    },
})
const visible=ref(props.isShow);
const inputVisible=ref(false);
const inputValue=ref('');
const dynamicTags=ref<any>([]);
const saveTagInput: Ref<any | null> = ref(null);
  watch(()=>visible.value,(newValue,oldValue)=>{
    emit('update:isShow', newValue)
  })
 
  const reverseArray : any=computed(()=>{
    return dynamicTags.value.slice().reverse() // 使用slice()来创建一个副本，然后反转它
  })
 const cancel=()=> {
      visible.value = false
    }
    // 搜索
    const querySearchAsync=async(queryString, cb)=> {
      const { code, data = {} } = await store.dispatch(
        'api/getEnterprise',
        {
          name: inputValue.value,
          pageNumber: 1,
          pageSize: 100,
        }
      )
      cb(data.list || [])
    }
   const handleSelect=(item)=> {
      inputValue.value = item.name
    }
   const cancelInput=()=> {
      setTimeout(() => {
        if (!inputValue.value) {
          inputVisible.value = false
        }
      }, 222)
    }
   const handleClose=(tag:any)=> {
      dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
    }
   const showInput=()=> {
      inputVisible.value = true
      nextTick(() => {
        saveTagInput.value.focus()
      })
    }
   const handleInputConfirm=()=> {
      const inputValues = inputValue.value
      if (inputValues) {
        const foundObject = dynamicTags.value.find(
          (item:any) => item.tag === inputValue
        )

        if (foundObject) {
          return ElMessage.error('输入标签已存在')
        }

        dynamicTags.value.push({
          tag: inputValue.value,
          modifiable: true,
        })
      }
      inputVisible.value = false
      inputValue.value = ''
    }

  const confirm=async()=> {
      if (!dynamicTags.value.length)
        return ElMessage.warning('请至少添加一个公司')

      const params = {
        assetIds: props.assetIds,
        selectType: props.selectType,
        assetType: props.searchData.searchType,
        condition: props.searchData.searchCondition,
        orderCondition: props.searchData.orderCondition,
        companies: dynamicTags.value.map((el) => el.tag),
        holdingRatio: props.searchData.holdingRatio,
      }

      if (props.batchCompanyType === 'conditionAddCompany') {
        const { code, data } = await store.dispatch(
          'api/addCompanyCondition',
          params
        )
        if (code === 0) {
          ElMessage.success('正在新增')
          emit('addCompanys')
          cancel()
        }
      }

      if (props.batchCompanyType === 'conditionDelCompany') {
        const { code, data } = await store.dispatch(
          'api/deleteCompanyCondition',
          params
        )
        if (code === 0) {
          ElMessage.success('正在删除')
          emit('addCompanys')
          cancel()
        }
      }
    }
</script>
<style lang="scss" scoped>
.asset-count {
  margin-bottom: 10px;
}
.tag-container {
  @include flexBox($justifyContent: flex-start);
  gap: $-v-spacing-horizontal-small; /* 设置子项之间的间距 */

  .el-input {
    max-width: 200px;
  }

  ::v-deep .el-input__icon {
    line-height: 26px;
    color: #d2deeb;
    cursor: pointer;
    &:hover {
      color: $-v-color-primary;
    }
  }

  .tag {
    display: flex;
    align-items: center;
    height: 26px;
    padding: 0 12px;
    font-size: 12px;
    color: #3aceff;
    border: 0.5px solid rgba(58, 206, 255, 0.6);
    border-radius: 4px;
    background: rgba(58, 206, 255, 0.1);
    max-width: 156px;

    > span {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      vertical-align: middle;
      white-space: nowrap;
    }
    &:hover:not(.tag-num) {
      background: rgba(58, 206, 255, 0.3);
      .tag-close {
        display: inherit;
      }
    }
    .tag-close {
      width: 12px;
      margin-left: 4px;
      display: none;
      cursor: pointer;
    }
  }

  .new-tag {
    display: flex;
    align-items: center;
    height: 26px;
    box-sizing: border-box;
    padding: 0 10px;
    font-size: 12px;
    line-height: 12px;
    color: $-v-color-primary;
    background: rgba(58, 125, 255, 0.1);
    border: 0.5px dashed $-v-color-primary;
    border-radius: 4px;
    cursor: pointer;
    &:hover {
      box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.3);
    }
  }
}
</style>
